<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建学习提醒' : "编辑学习提醒" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="提醒类别" prop="studyPlanType">
          <el-select v-model="ruleForm.studyPlanType" placeholder="请选择提醒类别">
            <el-option label="学习提醒" value="学习提醒" />
            <el-option label="上报提醒" value="上报提醒" />
          </el-select>
        </el-form-item>

        <el-form-item label="通知单位" prop="studyUnits">
          <el-input v-model="ruleForm.studyUnits" placeholder="请输入通知单位"></el-input>
        </el-form-item>

        <el-form-item label="学习主题" prop="studySubject">
          <el-select v-model="ruleForm.studySubject" placeholder="请选择学习主题">
            <el-option v-for="(sItem, sIndex) in learnSubject" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="发布日期" prop="pubDate">
          <el-date-picker
            v-model="ruleForm.pubDate"
            type="date"
            placeholder="请选择发布日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="提醒日期" prop="studyPlanDate">
          <el-date-picker
            v-model="ruleForm.studyPlanDate"
            type="dates"
            placeholder="请选择提醒日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
            @change="studyPlanDateChange"
          />
        </el-form-item>

        <el-form-item label="备注" prop="studyBak">
          <el-input v-model="ruleForm.studyBak" autosize type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendLearnRemindAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router'
import tEditor from "@/components/tinymceEditor/tEditor.vue"
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { format } from '@/plugins/moment.js'
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter()

onMounted(() => {
  /* 如果是编辑，查询详情填充表单项 */
  if(route.currentRoute.value.query.id){
    getRemindDetail()
  }
  getLearnSubject()

  /* 如果是从学习主题列表跳转过来，默认选中此主题 */
  if(route.currentRoute.value.query.subjectId){
    ruleForm.value.studySubject = route.currentRoute.value.query.subjectId
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getRemindDetail = () => {
  loading.value = true
  http.$GET("/TheoryStudyM/GetTheoryStudyPlanDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result.length) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[0][key] != null){
        ruleForm.value[key] = res.result[0][key];
      }
    })

    /* 提醒日期 */
    let arr = []
    res.result.forEach((item) => {
      arr.push(item.studyPlanDate)
    })
    if(arr.length) {
      ruleForm.value.studyPlanDate = arr
    }

    /* 处理发布日期 */
    ruleForm.value.pubDate = format(res.result[0].pubDate)
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 学习主题下拉列表请求 */
const learnSubject = ref([])
const subjectPageIndex = ref(1)
const subjectPageSize = ref(200)

const getLearnSubject = () => {
  let params = {
    pageIndex: subjectPageIndex.value,
    pageSize: subjectPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetTheoryStudySubjectLocalInfoList`, params).then(res => {
    learnSubject.value = learnSubject.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      subjectPageIndex.value = subjectPageIndex.value + 1
      getLearnSubject()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 禁选提醒日期 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

const orderSort = (a, b) => {
  return new Date(a).getTime() - new Date(b).getTime()
}

/* 提醒日期选择 */
const studyPlanDateChange = (val) => {
  ruleForm.value.studyPlanDate = val.sort(orderSort)
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单值 */
const ruleForm = ref({
  id: "",
  studyPlanType: "",
  studyUnits: "",
  studySubject: "",
  pubDate: "",
  studyPlanDate: "",
  studyBak: "",
})

/* 表单校验规则 */
const rules = reactive({
  studyPlanType: [
    { required: true, message: '请选择提醒类别', trigger: 'change' }
  ],
  studyUnits: [
    { required: true, message: '请输入通知单位', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studySubject: [
    { required: true, message: '请选择学习主题', trigger: 'change' }
  ],
  pubDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  studyPlanDate: [
    { required: true, message: '请选择提醒日期', trigger: 'change' }
  ],
  studyBak: [
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
})

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交新增、编辑 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 日期处理 */
      let params = JSON.parse(JSON.stringify(ruleForm.value))
      for(let k in params){
        if(k == 'studyPlanDate') {
          params.studyPlanDate = params[k].join(",")
        }
      }

      http.$POST("/TheoryStudyM/AddOrUpdateTheoryStudyPlanNews", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage({
            type: 'warning',
            message: '操作失败',
          })
        }else{
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          route.push({
            path: "/backend/learn-remind"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage({
          type: 'warning',
          message: '操作失败',
        })
      })
    }else{
      ElMessage({
        type: 'warning',
        message: '请先完成必填项',
      })
    }
  })
}

/* 重置表单项 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/learn-remind",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>